﻿using IM.Easy.Core.OAuth.OAuthUser;
using IM.Easy.Core.OAuth.ProvidersApi;
using IP2Region.Ex.Models;
using Mapster;
using Refit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.Core.OAuth.Providers
{
    public class GiteeOAuthProvider : AuthProviderAbstract
    {
        protected override string hostURL => "https://gitee.com";
        private readonly IGiteeApi oauthApi;

        public GiteeOAuthProvider(AuthOptions options) : base(options)
        {
            oauthApi = RestService.For<IGiteeApi>(hostURL);
        }


        public override Task<OAuthTokenResponse> GetAccessTokenAsync(string code, string redirectUri)
        {
            var parm = new OAuthTokenRequest
            {
                ClientId = Options.ClientId,
                ClientSecret = Options.ClientSecret,
                Code = code,
                RedirectUri = redirectUri
            };
            var response = oauthApi.GetAccessToken(parm);
            return response;
        }

        /// <summary>
        /// 回调地址
        /// </summary>
        /// <param name="redirectUri"></param>
        /// <returns></returns>
        public override string GetAuthorizationUrl(string redirectUri)
        {
            var queryParams = new Dictionary<string, string>
            {
                { "client_id", Options.ClientId },
                { "redirect_uri", redirectUri },
                { "response_type","code" },
                //{ "scope", config.Scope },
                { "state", ""},
                { "scope", "user_info projects emails"}
            };
            // 使用 UriBuilder 生成 URL
            var builder = new UriBuilder(hostURL)
            {
                Path = "/oauth/authorize",
                Query = BuildQueryString(queryParams)
            };
            return builder.ToString();
        }

        public override async Task<UserInfo> GetUserInfoAsync(string accessToken)
        {
            var user = await oauthApi.GetUserInfoAsync(accessToken);
            return user.Adapt<UserInfo>();
        }
    }
}
